#!/bin/bash

ACTION=
EXAM_NUMBER=

function usage {
    echo "Usage:"
    echo " -c             Generate C source file template"
    echo " -g             Generate .gitignore file template"
    echo " -h             Show this message and quit"
    echo " -n             Specify the question number"
    echo " -m             Generate Makefile template"
    exit 0
}

function makefile {
    cat <<EOF
EXAM_NUMBER=$EXAM_NUMBER
include ../SharedMakefile
EOF
}

function csource {
    cat <<EOF
/*
    XTU OJ: $EXAM_NUMBER
    Link: https://acm.xtu.edu.cn/exam/index.php/problem/exam_read/id/$EXAM_NUMBER
    by: fifth_light
*/

EOF
    cat <<EOF
#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>

int main(void) {
    int t;
    scanf("%d", &t);
    for(int i = 0; i < t; i++) {
        
    }
    return 0;
}
EOF
}

function gitignore {
cat <<EOF
$EXAM_NUMBER
$EXAM_NUMBER-2
$EXAM_NUMBER-3
$EXAM_NUMBER-4
classpath*
classpath*/*
table
table-2
table-3
table-4
table*.txt
$EXAM_NUMBER*-dbg
$EXAM_NUMBER*.brkpnt
$EXAM_NUMBER*.dbgcmd
EOF
}

while getopts :chn:gm opt; do
    case ${opt} in
        c)
            [[ "${ACTION}" != "" ]] && echo "Multiple action specified."
            ACTION=csource
            ;;
        n)
            [[ "$EXAM_NUMBER" != "" ]] && echo "Multiple number specified."
            EXAM_NUMBER="${OPTARG}"
            ;;
        g)
            [[ "${ACTION}" != "" ]] && echo "Multiple action specified."
            ACTION=gitignore
            ;;
        h)
            usage
            ;;
        m)
            [[ "${ACTION}" != "" ]] && echo "Multiple action specified."
            ACTION=makefile
            ;;
        *)
            printf "Invalid Option: %s.\n" "$1"
            usage
            ;;
     esac
done

if [ "${ACTION}" == "" ]; then
    echo "No action specified."
    usage
fi

if [ "${EXAM_NUMBER}" == "" ]; then
    echo "No question number specified."
    usage
fi

case ${ACTION} in
    makefile)
        makefile;
        ;;
    csource)
        csource;
        ;;
    gitignore)
        gitignore;
        ;;
esac
